const detectVerticalSquash = function(img) {
  var iw = img.naturalWidth,
    ih = img.naturalHeight;
  var canvas = document.createElement("canvas");
  canvas.width = iw;
  canvas.height = ih;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var data = ctx.getImageData(0, 0, 1, ih).data;
  var sy = 0;
  var ey = ih;
  var py = ih;
  while (py > sy) {
    var alpha = data[(py - 1) * 4 + 3];
    if (alpha === 0) {
      ey = py;
    } else {
      sy = py;
    }
    py = (ey + sy) >> 1;
  }
  var ratio = py / ih;
  return ratio === 0 ? 1 : ratio;
};

const drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
  var vertSquashRatio = detectVerticalSquash(img);
  ctx.drawImage(
    img,
    sx * vertSquashRatio,
    sy * vertSquashRatio,
    sw * vertSquashRatio,
    sh * vertSquashRatio,
    dx,
    dy,
    dw,
    dh
  );
};

const imgToBase64 = function(file, callback, params) {
  var prms = params || { width: 90, cut: 0.1, type: "jpeg" };
  var tmpImage = new Image(),
    base64Str = "";
  tmpImage.src = URL.createObjectURL(file);
  tmpImage.onload = function() {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    var width = tmpImage.width,
      height = tmpImage.height;
    var scale = width / height;
    var width1 = prms.width ? prms.width : 220;
    var height1 = parseInt(width1 / scale);
    canvas.width = width1;
    canvas.height = height1;
    if (navigator.userAgent.match(/iphone/i)) {
      drawImageIOSFix(
        context,
        tmpImage,
        0,
        0,
        width,
        height,
        0,
        0,
        width1,
        height1
      );
    } else {
      context.drawImage(tmpImage, 0, 0, width1, height1);
    }
    var realCut = prms.cut ? prms.cut : 0.1;
    base64Str = canvas.toDataURL("image/" + prms.type, realCut);
    callback & callback(base64Str);
  };
};

const Images = {
  toBase64: imgToBase64
};
export default Images;
